package com.beidouapp.mvc;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.beidouapp.common.enums.YesNoEnum;
import com.beidouapp.common.util.JSONUtils;
import com.beidouapp.domain.pojo.Employee;
import com.beidouapp.domain.pojo.Organization;
import com.beidouapp.domain.pojo.User;
import com.beidouapp.domain.vo.OrgRoleEmployeeVO;
import com.beidouapp.exception.BusinessException;
import com.beidouapp.security.model.ReturnDataInfo;
import com.beidouapp.security.model.SessionUser;
import com.beidouapp.security.utils.DscpCommUtils;
import com.beidouapp.service.EmployeeService;
import com.beidouapp.service.OrganizationService;
import com.beidouapp.service.UserService;

/**
 *  用户管理{论坛同步用户/咨询客户}
 */
@Controller
@RequestMapping(value = "/forum")
public class ForumController {

    private Logger logger = LoggerFactory.getLogger(ForumController.class);

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private UserService userService;

    @Autowired
    private OrganizationService organizationService;

    /**
     *  跳转到用户列表页面
     *  
     */
    @RequestMapping(value = "/page/list", method = RequestMethod.GET)
    public ModelAndView forward2EmpPage(HttpSession session) {
        ModelAndView view = new ModelAndView();
        boolean isSupperVisible = true;
        if (!DscpCommUtils.isSupperAdmin(session)) {
            isSupperVisible = false;
        }
        view.addObject("isSupperVisible", isSupperVisible);
        view.setViewName("member/member_list");
        return view;
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public
    @ResponseBody
    ReturnDataInfo<OrgRoleEmployeeVO> listMember(HttpSession session, HttpServletRequest request, @RequestParam(value = "iDisplayStart", required = false, defaultValue = "0") Integer offset, @RequestParam(value = "iDisplayLength", required = false, defaultValue = "10") Integer limit, @RequestParam(value = "globalSearch", required = false, defaultValue = "{}") String globalSearch) {
        try {
            Map paramters = new HashMap();
            if (globalSearch != null) {
                JSONObject jsonObject = JSONObject.fromObject(globalSearch);
                paramters.putAll(jsonObject);
            }
            paramters.putAll(request.getParameterMap());
            if (!DscpCommUtils.isSupperAdmin(session)) {
                Long current_orgId = DscpCommUtils.getSessionUser(session).getOrgId();
                if (current_orgId == null) {
                    throw new BusinessException("您没有权限操作此项！");
                }
                paramters.put("orgId", current_orgId);
            }
            String u = (String) paramters.get("userName");
            paramters.put("empName", u);
          /*  List<OrgRoleEmployeeVO> orgRoleEmployeeVO = employeeService.findOrgRoleEmployeesByMap(paramters, offset, limit);
            Integer totalCount = employeeService.findOrgRoleEmployeesCountByMap(paramters);*/
          /*  return ReturnDataInfo.createSuccessfulExecuteResults(orgRoleEmployeeVO, offset, limit, totalCount.longValue());*/
            return null;
        } catch (Exception ex) {
            logger.error("获取用户列表失败", ex);
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }


    /**
     *  
     *  //跳转到新增咨询客户页面
     *  
     */
    @RequestMapping(value = "/page/add", method = RequestMethod.GET)
    public ModelAndView addEmpPage(HttpSession session) {
        ModelAndView view = new ModelAndView();
        view.addObject("isManagerPlat", DscpCommUtils.isManagerPlat(session));
        Organization org = new Organization();
        org.setIsDel(YesNoEnum.No.getCode());
        List<Organization> orgList = new ArrayList<Organization>();
        if(DscpCommUtils.isManagerPlat(session)){
           orgList = organizationService.findOrganizationList(org);
        }
        else
        {
        	SessionUser member = DscpCommUtils.getSessionUser(session);
        	Organization organization = organizationService.getOrganizationById(member.getOrgId());
        	orgList.add(organization);
        }
        view.addObject("orgList", orgList);

        view.setViewName("member/member_add");
        return view;
    }


    /**
     * 修改密码页面跳转
     *
     */
    @RequestMapping(value = "/changePwd/{userId}", method = RequestMethod.GET)
    public ModelAndView changePwdPage(HttpSession session, @PathVariable Long userId) {
        ModelAndView view = new ModelAndView();
        view.addObject("userId", userId);
        view.setViewName("member/member_pwd");
        return view;
    }

    @RequestMapping(value = "/updatePwd", method = RequestMethod.POST, headers = "Content-Type=application/json")
    public
    @ResponseBody
    ReturnDataInfo<String> updatePwd(HttpSession session, HttpServletRequest request, @RequestBody Map<String, String> paramters) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            Long userId = mapper.convertValue(paramters.get("userId"), Long.class);
            String userPassword = mapper.convertValue(paramters.get("userpassword"), String.class);
            userService.resetPassword(userId, userPassword);
            return ReturnDataInfo.createSuccessfulSingleExecuteResult(null);
        } catch (Exception ex) {
            logger.error("resetPassword is failed.", ex);
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }


    @RequestMapping(value = "/page/{memberId}", method = RequestMethod.GET)
    public ModelAndView modifyMemberPage(HttpSession session, @PathVariable String memberId) {
        ModelAndView view = new ModelAndView();
/*        view.addObject("employeeId", memberId);
        view.addObject("isManagerPlat", DscpCommUtils.isManagerPlat(session));
        OrgRoleEmployeeVO vo = employeeService.getEmployeeVOById(memberId);
        Organization org = new Organization();
        org.setIsDel(YesNoEnum.No.getCode());
        List<Organization> orgList = new ArrayList<Organization>();
        if(DscpCommUtils.isManagerPlat(session)){
            orgList = organizationService.findOrganizationList(org);
         }
         else
         {
         	SessionUser member = DscpCommUtils.getSessionUser(session);
         	Organization organization = organizationService.getOrganizationById(member.getOrgId());
         	orgList.add(organization);
         }
        view.addObject("orgList", orgList);
        JSONObject jsonObject = JSONUtils.convert2Obj(vo);
        view.addObject("member", jsonObject.toString());*/
        view.setViewName("member/member_edit");
        return view;
    }


    @RequestMapping(value = "/add", method = RequestMethod.POST, headers = "Content-Type=application/json")
    public
    @ResponseBody
    ReturnDataInfo<String> addMember(HttpSession session, HttpServletRequest request, @RequestBody Map<String, Object> paramters) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            User user = mapper.convertValue(paramters.get("member"), User.class);
            Employee member = mapper.convertValue(paramters.get("member"), Employee.class);
            Long orgId = mapper.convertValue(paramters.get("orgId"), Long.class);
            Long roleId = mapper.convertValue(paramters.get("roleId"), Long.class);
            if (!DscpCommUtils.isSupperAdmin(session)) {
                Long current_orgId = DscpCommUtils.getSessionUser(session).getOrgId();
                if (current_orgId == null) {
                    throw new Exception("您没有权限操作此项！");
                }
            }

          employeeService.addEmployee(user, member, orgId, roleId);
            return ReturnDataInfo.createSuccessfulSingleExecuteResult(null);
        } catch (Exception ex) {
            logger.error("添加员工失败！", ex);
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }


 
    @RequestMapping(value = "/update", method = RequestMethod.POST, headers = "Content-Type=application/json")
    public
    @ResponseBody
    ReturnDataInfo<String> updateEmployee(HttpSession session, HttpServletRequest request, @RequestBody Map<String, Object> paramters) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            User user = mapper.convertValue(paramters.get("member"), User.class);
            Employee member = mapper.convertValue(paramters.get("member"), Employee.class);
            Long orgId = mapper.convertValue(paramters.get("orgId"), Long.class);
            Long roleId = mapper.convertValue(paramters.get("roleId"), Long.class);

            if (!DscpCommUtils.isSupperAdmin(session)) {
                Long current_orgId = DscpCommUtils.getSessionUser(session).getOrgId();
                if (current_orgId == null) {
                    throw new Exception("您没有权限操作此项！");
                }
            }
            employeeService.modifyEmployee(user, member, orgId, roleId);
            return ReturnDataInfo.createSuccessfulSingleExecuteResult(null);
        } catch (Exception ex) {
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }

}
